<template>
  <div class="chatbox">
    <div class="chat">
      <audio preload="auto" src="../../static/9411.mp3" id="audio"></audio>
      <header>
        <h1>石家庄金冠中医骨病医院（在线客服）</h1>
      </header>
      <main>
        <ul class="chatlist">
          <li
            v-for="(item,index) of onlinePatient"
            :key="item.patientId"
            @click="privateChat(item.patientId,index,item.patientName,item.chatId)"
            :class="showIndex==index?'default-active':''"
          >
            {{item.patientName}}
            <!-- <span :class="showTipsIndex==index?'tips':''"></span> -->
            <span class="tips" v-show="item.showTips"></span>
          </li>
        </ul>
        <div class="right_box">
          <!-- 消息列表 -->
          <ul class="container">
            <li v-for="(item,index) of messageList" :key="index">
              <!-- 时间 -->
              <div class="time">{{item.time}}</div>
              <div class="box">
                <!-- 左侧头像 -->
                <!-- 右侧消息栏 -->
                <div class="msgleft" :class="item.myCode?'':'msgright'">
                  <!-- 消息 -->
                  <div class="content" :class="item.myCode?'':'contentme'" v-html="item.msg"></div>
                </div>
              </div>
            </li>
          </ul>

          <footer>
            <!-- 头像列表 -->
            <ul class="icon_box" v-show="usericonseen">
              <li v-for="(item,index) of iconarr" :key="index">
                <img :src="item.src" alt="头像" @click="icon_item(item.src)">
              </li>
            </ul>
            <!-- 表情列表 -->
            <div class="emoji_list" v-show="seen">
              <ul>
                <li v-for="(item,index) of emoji" :key="index">
                  <img :src="item.src" :alt="item.src" @click="selfhtml(item.src)">
                </li>
              </ul>
            </div>
            <!-- 打开列表 -->
            <div class="options">
              <div class="emoji_box">
                <span class="emoji fa fa-smile-o" @click="showemoji"></span>
                <span class="emoji fa fa-photo" @click="readfile"></span>
                <span class="emoji fa fa-video-camera" @click="videoCamera"></span>
              </div>
              <el-checkbox v-model="noScroll" class="cookies_box">禁止滚动</el-checkbox>
            </div>
            <!-- 输入框 -->
            <div class="text_box">
              <div
                contenteditable="true"
                id="textarea"
                v-html="msgtext"
                ref="divtext"
                @keyup.enter="send"
              ></div>
            </div>
            <!-- 发送按钮 -->
            <button id="send" @click="send($event)">发送</button>
          </footer>
        </div>
      </main>
    </div>
  </div>
</template>
<script>
import $ from "jquery";
import Vue from "vue";
import axios from "axios";
// import flv from 'flv'
// 创建VueSocketIO
import VueSocketIO from "vue-socket.io";
import cookie from "js-cookie";
Vue.use(
  new VueSocketIO({
    debug: true,
    connection: "http://192.168.66.132:8080/"
  })
);

export default {
  name: "test",
  data() {
    return {
      // 默认的头像
      usericon: "../../static/images/portraiticon/100.jpg",
      // websock默认设置
      websock: null,
      // 接受数据的数组
      messageList: [],
      // 输入框数据
      msgtext: "",
      // 是否显示表情库
      seen: false,
      //头像列表显示
      usericonseen: false,
      // 用户名变量
      username: "",
      // 表情默认路径数组
      emoji: [],
      //用户选择的表情
      emojitext: "",
      // 头像列表
      iconarr: [],
      noScroll: false,
      // 是否显示视频
      showVideo: false,
      onlineName: [],
      // 接收方ID
      serviceId: "",
      //当前元素高亮
      showIndex: null,
      // 当前客服
      serviceName: "",
      // 当前咨询的患者
      onlinePatient: [],
      //之前的咨询的患者
      beforeOnlinePatient: [],
      // 当前点击的chatId
      chatId: "",
      // 最新消息提示
      showTipsIndex: null
    };
  },
  mounted() {
    // 链接到服务器
    this.$socket.connect();
    // 登录websocket
    this.$socket.emit("login", {
      username: cookie.get("username"),
      chatId: cookie.get("chatId")
    });
    // 调用表情方法
    this.emojis();
    // 接受服务器返回的数据
    this.sockets.subscribe("getChatId", data => {
      // 判断有没有设置对话ID
      if (!cookie.get("chatId")) {
        cookie.set("chatId", data.chatId);
      }
    });
    // 最新的在线患者
    this.sockets.subscribe("onlinePatients", data => {
      // 最新的在线患者数组
      this.onlinePatient = data.onlinePatient;
      // 自动发送迎宾语句
      // if (this.onlinePatient !='') {
      //   this.$socket.emit("private", {

      //     // mySocketId: data.onlinePatient[data.onlinePatient.length - 1].patientId,
      //     // chatId: data.onlinePatient[data.onlinePatient.length - 1].chatId,
      //     mySocketId: 'k7z73w_gOovLUZuJAABD',
      //     chatId: '5c52892178bc7e571948b346',
      //     msg: "您好！请问您想咨询什么问题",
      //     time: this.base.dateFtt("yyyy-MM-dd hh:mm:ss", new Date())
      //   });
      // }

      // this.newOnlinePatient = data.onlinePatient;
      // 循环最新的在线患者数组
      // data.onlinePatient.forEach((item, index) => {
      //   if (!this.onlinePatient.hasOwnProperty(item.chatId)) {
      //     // 现在线患者
      //     this.onlinePatient.push(item);
      //     console.log(index)
      //   }
      // });
    });
  },
  // websoket连接
  sockets: {
    connect: function() {
      console.log("连接服务器成功");
    },
    customEmit: function(data) {
      console.log(
        'this method was fired by the socket server. eg: io.emit("customEmit", data)'
      );
    }
  },
  updated() {
    // 在线姓名列表
    this.sockets.subscribe("onlineName", data => {
      this.username = cookie.get("username");
      data.forEach((item, index) => {
        if (item.username == cookie.get("username")) {
          data.splice(index, 1);
        }
      });
      this.onlineName = data;
    });
    // 接受私聊消息
    this.sockets.subscribe("privates", data => {
      /**
       * 如果客服当前的聊天窗口和最新消息用户
       * 是一个人就可以当前患者发送的消息，
       * 不是一人就不显示
       * */
      if (this.chatId == data.data[0].chatId) {
        this.messageList = data.data;
      } else {
        this.onlinePatient.forEach((item, index) => {
          if (item.chatId == data.data[0].chatId) {
            item.showTips = true;
            // this.showTipsIndex = index;
          }
        });
      }
      //播放音乐
      this.openPlayer();
    });
    // 判断是否自动滚动
    if (!this.noScroll) {
      this.$nextTick(() => {
        var container = this.$el.querySelector(".container");
        container.scrollTop = container.scrollHeight;
      });
    }
  },
  methods: {
    // 播放音乐
    openPlayer: function() {
      var audio = document.querySelector("#audio");
      audio.play();
    },
    // 渲染表情路径
    emojis() {
      for (var i = 1; i < 99; i++) {
        this.emoji.push({ src: "../../static/images/emoji/" + i + ".gif" });
      }
    },
    // 获取表情路径追加聊天窗口
    selfhtml(data) {
      // 获取img标签
      var imgHtml = "<img src=" + data + ">";
      // 把当前窗口的内容赋值给msgtext
      this.emojitext += imgHtml;
      this.msgtext =
        this.$refs.divtext.innerText.trim().replace(/[\r\n]/g, "") +
        this.emojitext;
      // 输入框的数据
      var msgdate = {
        msg: this.msgtext,
        time: this.base.dateFtt("yyyy-MM-dd hh:mm:ss", new Date())
      };

      // 输入框表情不能为空
      if (msgdate.msg != "") {
        // 判断如果是私聊就触发私聊 不是就 发送到群聊
        if (this.serviceId != "") {
          // 追加到当前数组中
          this.messageList.push(msgdate);
          // 发送到后台
          this.$socket.emit("private", {
            username: cookie.get("username"),
            mySocketId: this.$socket.id,
            serviceId: this.serviceId,
            serviceName: this.serviceName,
            chatId: cookie.get("chatId"),
            msg:
              this.$refs.divtext.innerText.trim().replace(/[\r\n]/g, "") +
              this.msgtext,
            time: this.base.dateFtt("yyyy-MM-dd hh:mm:ss", new Date()),
            usericon: cookie.get("usericon")
          });
        }
      }
      // 清空输入框
      this.$refs.divtext.innerText = this.msgtext = "";
      this.emojitext = "";
      // 隐藏表情框
      this.seen = false;
    },

    // 发送消息
    send(data) {
      // 要发送的数据
      var msgdate = {
        username: cookie.get("username"),
        mySocketId: this.$socket.id,
        serviceId: this.serviceId,
        serviceName: this.serviceName,
        chatId: this.chatId,
        msg:
          this.$refs.divtext.innerText.trim().replace(/[\r\n]/g, "") +
          this.msgtext,
        time: this.base.dateFtt("yyyy-MM-dd hh:mm:ss", new Date()),
        usericon: cookie.get("usericon")
      };
      // 输入框文字不能为空
      if (msgdate.msg != "") {
        if (this.serviceId != "") {
          // 追加到当前数组中
          this.messageList.push(msgdate);
          // 通过private发送给后台消息
          this.$socket.emit("private", msgdate);
        }
      }
      // 清空输入框
      this.$refs.divtext.innerText = this.emojitext = this.msgtext = "";
      //隐藏表情框
      this.seen = false;
    },
    // 点击切换查看咨询患者
    privateChat(socketId, index, username, chatId) {
      // 获取当前点击的索引
      this.showIndex = index;
      // 点击取消最新消息提示
      this.onlinePatient[index].showTips = false;
      this.showTips = false;
      // // 获取当前点击的socketId
      this.serviceId = socketId;
      // // 获取当前值班客服的
      this.serviceName = username;
      // 设置当前chatId 为点击的chatId
      this.chatId = chatId;
      // 点击查询当前客户的聊天记录
      var that = this;
      axios
        .get("api/getChat", {
          params: {
            chatId: chatId,
            currentSocketId: socketId
          }
        })
        .then(function(res) {
          that.messageList = res.data;
          console.log(res.data);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    showemoji() {
      this.seen = !this.seen;
    },
    // 发送图片
    readfile() {
      console.log("11");
    },
    videoCamera() {
      this.showVideo = !this.showVideo;
    }
  }
};
</script>

<style lang="stylus" scoped>
.chatbox {
  display: flex;

  .video_box {
    width: 500px;
    height: 300px;
    margin-left: 5px;

    #myPlayer {
      height: 100%;
      width: 100%;
    }
  }

  .chat {
    display: flex;
    flex-direction: column;
    position: relative;
    width: 880px;
    height: 100%;

    header {
      border: 1px solid #adadad;
      background: rgba(245, 245, 245, 0.9);
      display: flex;
      justify-content: space-between;
      padding: 5px 10px;

      h1 {
        text-align: left;
        line-height: 36px;
        font-size: 15px;
        padding-left: 10px;
        margin-bottom: 0;
      }

      .close {
        height: 36px;
        padding: 0px 4px;
      }
    }

    main {
      flex: 1;
      border: 1px solid #adadad;
      border-top: 0;
      background: rgba(245, 245, 245, 0.9);
      position: relative;
      overflow: auto;
      display: flex;

      .chatlist {
        background: #f0f0f0;

        li {
          height: 50px;
          line-height: 50px;
          border-bottom: 1px solid #adadad;
          padding: 0 30px 0 20px;
          width: 100px;

          span {
            width: 9px;
            height: 9px;
            display: inline-block;
          }
        }
      }

      .right_box {
        flex: 1;
        display: flex;
        flex-direction: column;
        border-left: 1px solid #adadad;

        .container {
          height: 100%;
          overflow: auto;
          padding: 10px 0 0 10px;
          flex: 1;

          li {
            margin-bottom: 10px;
            float: left;
            width: 100%;

            .box {
              overflow: hidden;

              .usericon {
                width: 36px;
                height: 36px;
                margin-right: 10px;
                border-radius: 3px;
                line-height: 36px;
                text-align: center;
                font-size: 40px;
                color: gray;
                float: left;

                img {
                  width: 36px;
                  height: 36px;
                  font-size: 12px;
                }
              }
            }

            .msgright {
              float: right !important;
            }

            .contentme {
              background: #9eea6a !important;
              float: right !important;
            }

            .time {
              color: gray;
              font-size: 14px;
              line-height: 24px;
              text-align: center;
            }

            .msgleft {
              float: left;
              margin-right: 10px;

              .username {
                color: gray;
                font-size: 14px;
                line-height: 24px;
              }

              .content {
                color: #333;
                font-size: 14px;
                line-height: 20px;
                background: #fff;
                display: inline-block;
                padding: 10px;
                border-radius: 5px;
                overflow: hidden;
                border: 1px solid #ededed;
              }
            }
          }
        }
      }

      .icon_box {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        background: #fff;
        justify-content: center;
        position: absolute;
        top: 0;
        left: 0;
        min-height: 200px;
        max-height: 400px;
        overflow: auto;
        border: 1px solid #adadad;

        li {
          width: 36px;
          height: 36px;
          margin: 3px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }

      .emoji_list {
        background: rgba(255, 255, 255, 1);
        position: absolute;
        bottom: 185px;
        left: 0;
        box-shadow: 0 0 5px #adadad;
        padding: 10px;
        z-index: 1;

        ul {
          display: flex;
          flex-wrap: wrap;

          li {
            width: 30px;
            height: 30px;
            line-height: 28px;
            overflow: hidden;
            text-align: center;
            float: left;

            .label {
              display: none;
            }
          }
        }
      }
    }

    footer {
      background: rgba(245, 245, 245, 0.9);
      width: 100%;
      display: flex;
      height: 180px;
      border-top: 0;
      position: relative;
      flex-direction: column;

      .options {
        height: 35px;
        width: 100%;
        background: rgba(245, 245, 245, 0.9);
        display: flex;
        justify-content: space-between;
        padding: 0 15px 0 10px;
        border-top: 1px solid #adadad;

        .emoji_box {
          position: relative;

          .fa-photo {
            font-size: 23px !important;
            margin-left: 0 !important;
          }

          .emoji {
            display: inline-block;
            margin: 5px;
            font-size: 26px;
          }

          .fa-video-camera {
            font-size: 22px;
          }
        }

        .cookies_box {
          line-height: 35px;
        }
      }

      .text_box {
        flex: 8.5;
        padding: 0 15px 40px 15px;

        #textarea {
          width: 100%;
          height: 100%;
          resize: none;
          border: 1px solid #adadad;
          overflow: auto;
        }
      }

      button {
        font-size: 16px;
        position: absolute;
        right: 5px;
        bottom: 5px;
        height: 30px;
        width: 60px;
        color: #666;
        background: #fff;
        border: 1px solid #adadad;
      }
    }
  }
}

.default-active {
  color: rgb(255, 208, 75);
  background-color: rgb(84, 92, 100);
}

.tips {
  background-color: #f56c6c;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  // height: 18px;
  // line-height: 18px;
  // padding: 0 3px;
  width: 9px;
  height: 9px;
  text-align: center;
  white-space: nowrap;
  border: 1px solid #fff;
  border-radius: 50%;
  // transform: translateY(-50%) translateX(0);
}
</style>
